/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.repair.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.DictCache;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.repair.entity.ElevatorStopLog;
import org.springblade.modules.repair.entity.MaintainPlanContent;
import org.springblade.modules.repair.enums.ElevatorStatusEnum;
import org.springblade.modules.repair.enums.ElevatorStopTypeEnum;
import org.springblade.modules.repair.enums.SourceEnum;
import org.springblade.modules.repair.service.IMaintainPlanContentService;
import org.springblade.modules.repair.vo.ElevatorStopLogVO;
import org.springblade.modules.repair.mapper.ElevatorStopLogMapper;
import org.springblade.modules.repair.service.IElevatorStopLogService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.service.IDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 电梯停梯状态日志 服务实现类
 *
 * @author ysq
 * @since 2022-10-09
 */
@Service
public class ElevatorStopLogServiceImpl extends BaseServiceImpl<ElevatorStopLogMapper, ElevatorStopLog> implements IElevatorStopLogService {

	@Autowired
	private IDictService DictService;
	@Autowired
	@Lazy
	private IMaintainPlanContentService planContentService;

	@Override
	public IPage<ElevatorStopLogVO> selectElevatorStopLogPage(IPage<ElevatorStopLogVO> page, ElevatorStopLogVO elevatorStopLog) {
		return page.setRecords(baseMapper.selectElevatorStopLogPage(page, elevatorStopLog));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean insertStopLog(ElevatorStopLog elevatorStopLog) {
		if(Func.isNotEmpty(elevatorStopLog.getModule())){
			MaintainPlanContent planContent = planContentService.getById(elevatorStopLog.getModule());
			elevatorStopLog.setStopType(ElevatorStopTypeEnum.getIdByPlanType(planContent.getTypeStatus()));
		}else {
			elevatorStopLog.setStopType(ElevatorStopTypeEnum.ELEVATOR_NON_FAULT.getId());
		}
		// 最新一次状态变更记录
		ElevatorStopLog latestLog = baseMapper.getLatestLog(elevatorStopLog.getElevatorId());
		boolean changeFlag = false;
		if (Func.isNotEmpty(latestLog)) {
			changeFlag = true;
			if (Func.equalsSafe(elevatorStopLog.getSetStatus(), latestLog.getSetStatus())) {
				return Boolean.TRUE;
			}
		}
		// 2024-08-19 新增当为空值的情况设置运行默认值
		if(Func.isNull(elevatorStopLog.getSetStatus())){
			elevatorStopLog.setSetStatus(ElevatorStatusEnum.NORMAL.getStatus());
		}
		if (ElevatorStatusEnum.STOP.getStatus() == elevatorStopLog.getSetStatus()) {
			elevatorStopLog.setStopReasonAncestors(this.getDictStopReasonAncestors(elevatorStopLog.getStopReason()));
			elevatorStopLog.setStopReasonName(DictCache.getValue(STOP_ELEVATOR_STATUS_DICT_KEY, elevatorStopLog.getStopReason()));
		}
		elevatorStopLog.setSource(SourceEnum.MAINTAIN_MINIAPP.getId());
		elevatorStopLog.setPlatform(0);
		if (this.save(elevatorStopLog)) {
			if (changeFlag) {
				// 耗时
				Duration duration = DateUtil.between(latestLog.getCreateTime(), elevatorStopLog.getCreateTime());
				// 更新上个状态耗时
				latestLog.setDuration(duration.getSeconds());
				int version = latestLog.getVersion();
				latestLog.setVersion(version + 1);
				this.update(latestLog, Wrappers.<ElevatorStopLog>lambdaUpdate().eq(ElevatorStopLog :: getId, latestLog.getId()).eq(ElevatorStopLog :: getVersion, version));
			}
			return true;
		}

		return false;
	}

	/**
	 * 查询停梯原因key祖级列表
	 * @param dictKey
	 * @return
	 */
	private String getDictStopReasonAncestors(String dictKey) {
		if (Func.isBlank(dictKey)) {
			return null;
		}

		LinkedList<String> ancestors = new LinkedList<>();
		Dict dict = DictService.getOne(Wrappers.<Dict>lambdaQuery().eq(Dict :: getCode, STOP_ELEVATOR_STATUS_DICT_KEY).eq(Dict::getDictKey, dictKey), false);
		if (Func.isNotEmpty(dict)) {
			List<Dict> dictList = DictCache.getList(STOP_ELEVATOR_STATUS_DICT_KEY);
			Map<Long, Dict> map = dictList.stream().collect(Collectors.toMap(t -> t.getId(), t -> t));
			Dict parentDict = map.get(dict.getParentId());
			while (Func.isNotEmpty(parentDict)) {
				ancestors.add(parentDict.getDictKey());
				parentDict = map.get(parentDict.getParentId());
			}
		}
		// 倒序
		Collections.reverse(ancestors);
		return Func.isEmpty(ancestors) ? null : ancestors.stream().collect(Collectors.joining(","));
	}
}
